<template>
  <s-clean-layout navbar="none" tabbar="/pages/index/contact">
    <view class="page-container">
      <!-- 自定义导航栏 -->
      <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
        <view class="navbar-left" @tap="goBack">
          <uni-icons type="left" size="20" color="#333"/>
        </view>
        <view class="navbar-center">
          <view class="tag-info">
            <view class="tag-color" :style="{ backgroundColor: tagColor }"/>
            <text class="tag-name">{{ tagName }}</text>
            <text class="contact-count">({{ contactList.length }}人)</text>
          </view>
        </view>
        <view class="navbar-right"></view>
      </view>

      <!-- 搜索区域 -->
      <view class="search-area" :style="{ marginTop: (statusBarHeight + 44) + 'px' }">
        <view class="search-box">
          <uni-icons class="search-icon" type="search" size="16" color="#999999" />
          <input class="search-input" v-model="searchText" placeholder="搜索联系人" @input="handleSearch" @confirm="handleSearch" />
          <uni-icons v-if="searchText" class="clear-icon" type="clear" size="16" color="#999999" @click="clearSearch" />
        </view>
      </view>

      <!-- 联系人列表 -->
      <scroll-view class="content" scroll-y>
        <view v-if="loading" class="loading-container">
          <text>加载中...</text>
        </view>
        <view v-else-if="filteredContactList.length === 0" class="empty-state">
          <uni-icons type="info" size="50" color="#999"/>
          <text class="empty-text">{{ searchText ? '未找到匹配的联系人' : '该标签下暂无联系人' }}</text>
        </view>
        <view v-else class="contact-list">
          <view v-for="contact in filteredContactList" :key="contact.id" class="contact-item" @click="viewContactDetail(contact)">
            <view class="contact-avatar">
              <image v-if="contact.avatarUrl" class="avatar" :src="contact.avatarUrl" mode="aspectFill"/>
              <view v-else class="avatar-placeholder">
                <text>{{ getNameInitial(contact.name) }}</text>
              </view>
            </view>
            <view class="contact-info">
              <text class="contact-name">{{ contact.name }}</text>
              <text v-if="contact.phoneNumber" class="contact-phone">{{ contact.phoneNumber }}</text>
              <!-- 联系人标签列表 -->
              <view v-if="contact.tagList && contact.tagList.length > 0" class="contact-tags">
                <view 
                  v-for="tag in contact.tagList" 
                  :key="tag.id" 
                  class="contact-tag"
                  :style="{ backgroundColor: tag.color || '#CCCCCC' }"
                >
                  <text class="tag-text">{{ tag.tagName }}</text>
                </view>
              </view>
            </view>
            <view class="contact-actions">
              <view class="action-btn delete-btn" @click.stop="handleDeleteContact(contact)">
                <uni-icons type="trash" size="18" color="#ff4757"/>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 悬浮添加按钮 -->
      <view class="floating-btn" @tap="showAddContactSelector">
        <text class="btn-icon">+</text>
      </view>

      <!-- 联系人选择器 -->
      <s-contact-selector
        v-model:visible="showContactSelector"
        title="选择联系人"
        :multiple="true"
        v-model="selectedContacts"
        @confirm="handleContactSelected"
        @cancel="handleContactCancel"
      />
    </view>
  </s-clean-layout>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import TagApi from '@/sheep/api/tag/tag.js';
import ContactApi from '@/sheep/api/contact/contact';
import SContactSelector from '@/sheep/components/s-contact-selector/s-contact-selector.vue';

export default {
  name: 'TagContactList',
  components: {
    SContactSelector
  },
  setup() {
    const statusBarHeight = ref(20);
    const tagId = ref(null);
    const tagName = ref('');
    const tagColor = ref('#CCCCCC');
    const contactList = ref([]);
    const searchText = ref('');
    const loading = ref(false);
    const showContactSelector = ref(false);
    const selectedContacts = ref([]);

    // 过滤后的联系人列表
    const filteredContactList = computed(() => {
      if (!searchText.value.trim()) {
        return contactList.value;
      }
      const keyword = searchText.value.toLowerCase();
      return contactList.value.filter(contact => 
        contact.name.toLowerCase().includes(keyword) ||
        (contact.phoneNumber && contact.phoneNumber.includes(keyword))
      );
    });

    // 获取状态栏高度
    const getSystemInfo = () => {
      const sysInfo = uni.getSystemInfoSync();
      statusBarHeight.value = sysInfo.statusBarHeight;
    };

    // 获取姓名首字母
    const getNameInitial = (name) => {
      if (!name) return '?';
      return name.charAt(0).toUpperCase();
    };

    // 返回上一页
    const goBack = () => {
      uni.navigateBack();
    };

    // 清除搜索
    const clearSearch = () => {
      searchText.value = '';
    };

    // 处理搜索
    const handleSearch = () => {
      // 本地搜索，无需额外处理，computed会自动过滤
    };

    // 获取标签下的联系人列表
    const fetchTagContacts = async () => {
      if (!tagId.value && tagId.value !== 0) return;
      
      loading.value = true;
      try {
        const res = await ContactApi.queryContacts({
          tagId: tagId.value,
          searchContent: ""
        });
        if (res.code === 0 && res.data) {
          contactList.value = res.data;
        } else {
          contactList.value = [];
          uni.showToast({
            title: res.msg || '获取联系人列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取标签联系人失败:', error);
        contactList.value = [];
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        loading.value = false;
      }
    };

    // 显示添加联系人选择器
    const showAddContactSelector = () => {
      selectedContacts.value = [];
      showContactSelector.value = true;
    };

    // 处理联系人选择确认
    const handleContactSelected = async (contacts) => {
      if (contacts.length === 0) return;
      
      try {
        uni.showLoading({ title: '添加中...' });
        const contactIds = contacts.map(contact => contact.id);
        
        const res = await TagApi.batchSetTagContact({
          tagId: tagId.value,
          contactIds: contactIds
        });
        
        if (res.code === 0) {
          uni.showToast({ title: '添加成功', icon: 'success' });
          // 重新获取联系人列表
          await fetchTagContacts();
        } else {
          uni.showToast({ title: res.msg || '添加失败', icon: 'none' });
        }
      } catch (error) {
        console.error('添加联系人到标签失败:', error);
        uni.showToast({ title: '添加失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    };

    // 处理联系人选择取消
    const handleContactCancel = () => {
      selectedContacts.value = [];
    };

    // 删除联系人
    const handleDeleteContact = (contact) => {
      uni.showModal({
        title: '确认删除',
        content: `确定要将"${contact.name}"从该标签中移除吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '删除中...' });
              const response = await TagApi.batchDelTagContact({
                tagId: tagId.value,
                contactIds: [contact.id]
              });
              
              if (response.code === 0) {
                uni.showToast({ title: '移除成功', icon: 'success' });
                // 重新获取联系人列表
                await fetchTagContacts();
              } else {
                uni.showToast({ title: response.msg || '移除失败', icon: 'none' });
              }
            } catch (error) {
              console.error('从标签移除联系人失败:', error);
              uni.showToast({ title: '移除失败', icon: 'none' });
            } finally {
              uni.hideLoading();
            }
          }
        }
      });
    };

    // 查看联系人详情
    const viewContactDetail = (contact) => {
      uni.navigateTo({
        url: `/pages/contact/detail?id=${contact.id}`
      });
    };

    // 页面加载时的初始化
    onMounted(() => {
      getSystemInfo();
      
      // 获取页面参数
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const options = currentPage.options || {};
      
      tagId.value = options.tagId ? parseInt(options.tagId) : null;
      tagName.value = decodeURIComponent(options.tagName || '标签');
      tagColor.value = decodeURIComponent(options.tagColor || '#CCCCCC');
      
      // 获取联系人列表
      if (tagId.value !== null && tagId.value !== undefined) {
        fetchTagContacts();
      }
    });

    return {
      statusBarHeight,
      tagId,
      tagName,
      tagColor,
      contactList,
      filteredContactList,
      searchText,
      loading,
      showContactSelector,
      selectedContacts,
      getNameInitial,
      goBack,
      clearSearch,
      handleSearch,
      showAddContactSelector,
      handleContactSelected,
      handleContactCancel,
      handleDeleteContact,
      viewContactDetail
    };
  }
};
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: #f8f9fc;
  height: 100vh;
  padding: 0;
  margin: 0;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  z-index: 100;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);

  .navbar-left {
    width: 44px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  .navbar-center {
    flex: 1;
    display: flex;
    justify-content: center;

    .tag-info {
      display: flex;
      align-items: center;
      gap: 8px;

      .tag-color {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
      }

      .tag-name {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

      .contact-count {
        font-size: 14px;
        color: #666;
      }
    }
  }

  .navbar-right {
    width: 44px;
  }
}

.search-area {
  padding: 20rpx 0;
  background-color: #FFFFFF;

  .search-box {
    display: flex;
    align-items: center;
    background-color: #F5F5F5;
    padding: 16rpx 20rpx;
    border-radius: 8rpx;
    margin: 0 16rpx;

    .search-icon {
      width: 16px;
      height: 16px;
      margin-right: 16rpx;
    }

    .search-input {
      flex: 1;
      font-size: 14px;
    }

    .clear-icon {
      width: 16px;
      height: 16px;
      margin-left: 16rpx;
    }
  }
}

.content {
  flex: 1;
  padding: 0;
  margin-bottom: 120rpx;
}

.loading-container, .empty-state {
  height: 400rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20rpx;

  .empty-text {
    color: #999999;
    font-size: 14px;
  }
}

.contact-list {
  .contact-item {
    background-color: #ffffff;
    border-radius: 0;
    margin-bottom: 16rpx;
    padding: 24rpx 16rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 2rpx 12rpx rgba(43, 127, 243, 0.05);
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.98);
      box-shadow: 0 4rpx 16rpx rgba(43, 127, 243, 0.12);
    }

    .contact-avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 24rpx;

      .avatar {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }

      .avatar-placeholder {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
        display: flex;
        align-items: center;
        justify-content: center;

        text {
          color: #fff;
          font-size: 14px;
          font-weight: 600;
        }
      }
    }

    .contact-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .contact-name {
        font-size: 16px;
        color: #333;
        font-weight: 500;
        margin-bottom: 8rpx;
      }

      .contact-phone {
        font-size: 14px;
        color: #666;
      }

      .contact-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8rpx;
        margin-top: 8rpx;

        .contact-tag {
          display: inline-flex;
          align-items: center;
          padding: 4rpx 12rpx;
          border-radius: 12rpx;
          min-height: 24rpx;

          .tag-text {
            font-size: 12px;
            color: #fff;
            line-height: 1;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            white-space: nowrap;
          }
        }
      }
    }

    .contact-actions {
      display: flex;
      align-items: center;

      .action-btn {
        padding: 16rpx;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background-color 0.2s ease;

        &.delete-btn:active {
          background-color: rgba(255, 71, 87, 0.1);
        }
      }
      .action-btn.delete-btn {
        margin-right: 16rpx;
      }
    }
  }
}

.floating-btn {
  position: fixed;
  right: 30rpx;
  bottom: 160rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #2B7FF3, #5A9CFF);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 20rpx rgba(43, 127, 243, 0.35);
  z-index: 100;
  transition: all 0.3s ease;

  .btn-icon {
    color: #fff;
    font-size: 50rpx;
    font-weight: 300;
    text-shadow: 0 1px 3px rgba(0,0,0,0.1);
  }

  &:active {
    transform: scale(0.9);
    box-shadow: 0 4rpx 16rpx rgba(43, 127, 243, 0.5);
  }
}
</style> 